<!--
 * @Author: 冯本桥
 * @Date: 2025-02-13 13:42:33
 * @LastEditTime: 2025-03-06 11:27:15
 * @LastEditors: 冯本桥
 * @Description: 线索管理
 * @FilePath: \teach_system_fe\src\views\sellCrm\clue.vue
-->
<template>
  <div v-loading="loading">
    <div class="cad-box">
      <el-form
        ref="ruleForm"
        :inline="true"
        :model="searchValue"
        class="demo-form-inline"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="" prop="channelId">
              <el-select
                v-model="searchValue.channelId"
                style="width: 100%"
                clearable
                placeholder="请选择线索来源"
              >
                <el-option
                  v-for="(item, index) in fromConfig.clueAddFrom[0].option"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" prop="rankp">
              <el-select
                v-model="searchValue.rankp"
                style="width: 100%"
                clearable
                placeholder="请选择线索级别"
              >
                <el-option
                  v-for="(item, index) in fromConfig.rankp"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" prop="zhwysStatus">
              <el-select
                v-model="searchValue.zhwysStatus"
                style="width: 100%"
                clearable
                placeholder="请选择线索状态"
              >
                <el-option
                  v-for="(item, index) in fromConfig.zhwysStatus"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" prop="name">
              <el-input
                v-model="searchValue.name"
                clearable
                placeholder="请输入家长姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" prop="mobile">
              <el-input
                v-model="searchValue.mobile"
                clearable
                placeholder="请输入联系方式"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="content-table cad-box">
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="add">添加线索</el-button>
        </el-col>
        <el-col :span="2.8">
          <el-button
            class="btn-primary-box"
            @click="download"
          >下载导入模板</el-button>
        </el-col>
        <el-col :span="2">
          <el-upload
            style="margin-left: 5px"
            action="/api/crm/web/leads/importLeadsExcel"
            name="files"
            accept=".xlsx,.xls"
            class="upload-demo"
            :multiple="false"
            :show-file-list="false"
            :headers="headerObj"
            :on-success="onSuccess"
            :on-progress="onProgress"
            :on-error="onError"
          >
            <el-button class="btn-primary-box">导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="6" />
      </el-row>

      <el-table
        :data="tableData"
        style="width: 100%; margin: 30px 0"
        :header-cell-style="{
          backgroundColor: '#fafafc',
          color: '#000000',
        }"
      >
        <el-table-column
          v-for="(item, index) in fromConfig.tableTitle"
          :key="index"
          :prop="item.key"
          :label="item.name"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-if="item.slot"
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <div
                v-if="
                  scope.row[item.key] !== '' && scope.row[item.key] !== null
                "
                :style="{
                  backgroundColor: item.option[scope.row[item.key]],
                }"
                class="state-box"
              />
              <span> {{ tableSlotValue(item.key, scope.row[item.key]) }}</span>
            </span>
            <span v-else-if="item.times">{{ times(scope.row[item.key]) }}</span>
            <span v-else-if="!item.slot">{{
              scope.row[item.key] == "null" ? "-" : scope.row[item.key] || "-"
            }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="info(scope.row.id)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-sizes="[10, 15, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-drawer
      title="添加线索"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
      size="35%"
    >
      <div style="padding: 0 30px">
        <from-page
          ref="addFromRef"
          :label-width="null"
          :rules="fromConfig.rules"
          :from-config="fromConfig.clueAddFrom"
          @submitForm="submitForm"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import * as fromConfig from './config'
import FromPage from '@/components/Basic/FromPage/index'
import { mapGetters } from 'vuex'
import { dictMixin } from '@/mixins'
import { getToken } from '@/utils/auth'
import { Submit, addSubmit } from './api/clue'

const templateUrl =
  'https://res.xxwbaby.com/public/%E7%BA%BF%E7%B4%A2%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls'
export default {
  components: {
    FromPage
  },
  mixins: [dictMixin],
  data () {
    return {
      fromConfig: fromConfig,
      headerObj: {
        Authorization: getToken(),
        ticket: getToken()
      },
      drawer: false,
      loading: false,
      fileList: [],
      searchValue: {},
      ruleForm: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      pagination: {
        pageNum: 0,
        pageSize: 10
      },
      tableData: [],
      total: 0
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    tableSlotValue () {
      return (key, value) => {
        if (value === null || value === 'null') {
          return '-'
        }
        return (
          this.fromConfig[key].find((item) => item.value * 1 === value * 1)
            ?.label || ''
        )
      }
    },
    times () {
      return (value) => {
        return value ? dayjs(value).format('YYYY/MM/DD') : '-'
      }
    }
  },
  created () {
    this.getTableList()
  },
  mounted () {},
  methods: {
    add () {
      this.drawer = true
      console.log('添加线索')
    },

    download () {
      console.log('下载导入模板')
      window.open(templateUrl, '_blank')
    },

    info (id) {
      this.$router.push({ path: '/sellCrm/clue/info', query: { id: id }})
    },

    onSubmit () {
      console.log('搜索')
      this.getTableList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    submitForm (formName) {
      if (formName !== '') {
        const {
          homeAddress: { province, city, area },
          ...listDate
        } = formName
        const list = { ...listDate }

        list.homeAddress = `${province.value || ''}${city.value || ''}${
          area.value || ''
        }${formName.address || ''}`

        this.addTableItem(list)
      }
    },

    beforeClose () {
      this.$refs.addFromRef.resetFields()
      this.drawer = false
    },

    async getTableList () {
      this.loading = true
      try {
        const siz = JSON.parse(JSON.stringify(this.pagination.pageNum))
        const res = await Submit({
          ...this.pagination,
          ...this.searchValue,
          pageNum: siz ? siz - 1 : siz,
          areaId: this.curArea.areaId || ''
        })
        this.tableData = res.content
        this.total = res.totalElements
      } catch (error) {
        // this.$message.error(error);
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    async addTableItem (value) {
      try {
        await addSubmit(value)
        this.$message.success('新增成功')
      } catch (error) {
        console.log(error)
      } finally {
        this.drawer = false
        this.getTableList()
      }
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getTableList()
    },
    handleCurrentChange (val) {
      this.pagination.pageNum = val
      this.getTableList()
    },

    onSuccess (response, file, fileList) {
      if (response.code !== '000000') {
        this.$message.error(response.msg)
      } else {
        this.$message.success('上传成功')
        this.getTableList()
      }
      this.loading = false
    },

    onProgress (event, file, fileList) {
      this.loading = true
    },

    onError () {
      this.$message.error('上传失败')
      this.loading = false
    }
  }
}
</script>

<style scoped lang="scss">
.content-table {
  margin-top: 20px;

  .state-box {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 10px;
  }
}

.demo-form-inline {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
</style>
